package com.digitalchina.lxnsy.base;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.LoginGuideActivity;
import com.digitalchina.lxnsy.activity.old.MainActivity;
import com.digitalchina.lxnsy.entity.PointVO;
import com.digitalchina.lxnsy.interfaces.IBaseTemplate;
import com.digitalchina.lxnsy.sy.login.LoginActivity;
import com.digitalchina.lxnsy.sy.login.RegisterAndLoginActivity;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.ToastUtil;
import com.digitalchina.lxnsy.toolkit.statusbar.StatusBarUtil;
import com.digitalchina.lxnsy.toolkit.statusbar.SystemBarTintManager;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.digitalchina.lxnsy.xml.UserXML;
import com.lzy.okhttputils.OkHttpUtils;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;
import com.nispok.snackbar.listeners.ActionClickListener;

import org.apache.http.params.HttpParams;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.List;

import butterknife.ButterKnife;
import wendu.dsbridge.DWebView;


/**
 * ================================================
 * 项目名称：bigdata
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2016/10/10 13:59
 * 修改备注：
 * ================================================
 */

public abstract class BaseActivity extends AppCompatActivity implements IBaseTemplate {

    // 标题栏
    protected ViewGroup mViewGroupActionBar;
    // 子布局
    protected ViewGroup mViewGroupContent;
    // 标题
    protected TextView mTextViewTitle;
    // 左侧按钮
    protected ImageView mIvBack;
    // 右侧图片按钮 mIvRight在最右边 mIvRight2在mIvRight的左边
    protected ImageView mIvRight, mIvRight2;
    // 右侧文字按钮
    protected TextView mTvRight;
    // handler
    protected Handler mHandler;
    // 加载框
    protected ProgressDialog dialog;
    // hybrid
    protected DWebView baseDWebView;

    protected LayoutInflater mInflater;
    // 访问接口参数
    protected HttpParams params;
    // 是否全屏
    protected boolean isFullscreen = false;

    // 是否禁止旋转屏幕
    private boolean isAllowScreenRotation = true;

    protected Activity activity;

    // F-Failed S-Success
    protected final int MSG_F_0 = 1001;
    protected final int MSG_S_0 = 1002;
    protected final int MSG_F_1 = 1003;
    protected final int MSG_S_1 = 1004;
    protected final int MSG_F_2 = 1005;
    protected final int MSG_S_2 = 1006;
    protected final int MSG_F_3 = 1007;
    protected final int MSG_S_3 = 1008;
    protected final int MSG_F_4 = 1009;
    protected final int MSG_S_4 = 1010;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            boolean result = fixOrientation();
        }
        super.onCreate(savedInstanceState);
        activity = BaseActivity.this;
//        fullscreen();
        setContentView(R.layout.activity_base);
        initMethods();
        ActivityTaskManager.getInstance().addActivity(this);
      //  LogUtils.e(this.getLocalClassName());
    }

    private void fullscreen() {

        if (isFullscreen) {
            //取消标题栏
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            //取消状态栏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    private boolean isTranslucentOrFloating(){
        boolean isTranslucentOrFloating = false;
        try {
            int [] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean)m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }


    private boolean fixOrientation(){
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo)field.get(this);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void setRequestedOrientation(int requestedOrientation) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            return;
        }
        super.setRequestedOrientation(requestedOrientation);
    }

    private void initMethods() {
        mInflater = LayoutInflater.from(this);
        setSysSettings();
        initBaseMember();
        setOnClickListener();
        dealSequence();
    }

    public void setSysSettings() {

        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary), 0); //设置状态栏颜色, 透明度为38

        if (isAllowScreenRotation) {
            setScreenOrientation();
        }
    }

    /**
     * 初始化base界面控件
     */
    protected void initBaseMember() {
        mInflater = LayoutInflater.from(this);
        mViewGroupActionBar = (ViewGroup) findViewById(R.id.base_activity_actionbar);
        mViewGroupContent = (ViewGroup) findViewById(R.id.layout_center);
        mTextViewTitle = (TextView) findViewById(R.id.actionbar_tv_title);
        mIvBack = (ImageView) findViewById(R.id.actionbar_iv_back);
        mIvRight = (ImageView) findViewById(R.id.actionbar_iv_right);
        mIvRight2 = (ImageView) findViewById(R.id.actionbar_iv_right2);
        mTvRight = (TextView) findViewById(R.id.actionbar_tv_right);
        baseDWebView = (DWebView) findViewById(R.id.base_dweb_view);


        baseDWebView.addJavascriptObject(new JsApiApp(), "app");

        com.tencent.smtt.sdk.WebSettings webSettings=baseDWebView.getSettings();
        //允许webview对文件的操作
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        //用于js调用Android
        webSettings.setJavaScriptEnabled(true);
        //设置编码方式
        webSettings.setDefaultTextEncodingName("utf-8");

        baseDWebView.loadUrl("file:///android_asset/html/base.html");

        mTvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rightOnClick();
            }
        });

        mIvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rightOnClick();
            }
        });

        mIvRight2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rightOnclick2();
            }
        });

    }

    protected void callJsMethod(String method) {
        baseDWebView.callHandler(method, new String[]{""});
    }

    protected void callJsMethod(String method, String[] agrs) {
        baseDWebView.callHandler(method, agrs);
    }

    public class JsApiApp {

    }


    /**
     * 修改actionBar的样式
     */
    protected void setBaseActivityTitleBar() {
        mViewGroupActionBar.setBackgroundResource(R.color.app_activity_bar_background);
        mTextViewTitle.setTextColor(getResources().getColor(R.color.app_activity_bar_font));
        mTvRight.setTextColor(getResources().getColor(R.color.app_activity_bar_font));
    }


    /**
     * 实现返回按钮监听
     */
    private void setOnClickListener() {
        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AdminXML.getUserType(activity).equals("1")) {
                    // 企业管理员
                    finish();
                } else {
                    // 普通用户
                    if (!ActivityTaskManager.getInstance().hasActivity(MainActivity.class))
                        GotoUtil.gotoActivity(BaseActivity.this, MainActivity.class);
                    finish();
                }

            }
        });
    }

    /**
     * 设置屏幕方向
     */
    protected void setScreenOrietation() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /**
     * 右上角第二个按钮监听
     */
    protected void rightOnclick2() {
    }

    /**
     * 设置内容区域
     *
     * @param layoutResID 资源文件ID
     */
    protected void setContentLayout(int layoutResID) {
        clearContentView();
        getLayoutInflater().inflate(layoutResID, mViewGroupContent, true);
        ButterKnife.bind(this);
    }

    /**
     * 设置内容区域
     *
     * @param view View对象
     */
//    protected void setContentLayout(View view) {
//        if (null != mViewGroupContent) {
//            mViewGroupContent.addView(view);
//        }
//    }

    /**
     * 清空view
     */
    private void clearContentView() {
        mViewGroupContent.removeAllViews();
    }


    /**
     * [是否允许屏幕旋转]
     *
     * @param isAllowScreenRotation
     */
    public void setScreenRoate(boolean isAllowScreenRotation) {
        this.isAllowScreenRotation = isAllowScreenRotation;
    }

    /**
     * 设置状态栏透明
     *
     * @param activity
     */
    public void setStatusBarTranslucent(Activity activity) {
        // 状态栏透明, 4.4+生效
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            SystemBarTintManager systemBarTintManager = new SystemBarTintManager(activity);
            systemBarTintManager.setStatusBarTintEnabled(true);
//            systemBarTintManager.setStatusBarTintResource(android.R.color.transparent);
        }
    }

    /**
     * 设置屏幕方向
     */
    public void setScreenOrientation() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }

    /***
     * 四个方法的执行顺序
     */
    public void dealSequence() {

        setHandler();
        setLayout();
        initMember();
        addListener();

    }

    /**
     * 显示加载框
     *
     * @param message
     */
    protected void showDialog(String message) {
        if (dialog == null)
            dialog = CustomDialog.progressDialog(this, message);
        if (dialog != null && !dialog.isShowing())
            dialog.show();
    }

    /**
     * 隐藏加载框
     */
    protected void dismissDialog() {
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();
    }

    /**
     * 提示语
     *
     * @param strMsg
     */
    protected void showToast(String strMsg) {
        ToastUtil.showToast(BaseActivity.this, strMsg);
    }

    /**
     * 提示语
     *
     * @param strMsg
     */
    protected void showSnackbar(String strMsg) {
        SnackbarManager.show(
                Snackbar.with(this)
                        .actionLabel("收起")
                        .actionColor(getResources().getColor(R.color.app_color))
                        .actionListener(new ActionClickListener() {
                            @Override
                            public void onActionClicked(Snackbar snackbar) {
                                dismissDialog();
                            }
                        })
                        .text(strMsg)
                        .position(Snackbar.SnackbarPosition.TOP), mViewGroupContent
        );


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && data.hasExtra("pointVOList")) {
            List<PointVO> pointVOList = (List<PointVO>) data.getSerializableExtra("pointVOList");
            if (pointVOList != null && pointVOList.size() > 0) {
                for (int i = 0; i < pointVOList.size(); i++) {
                    final Dialog dialog = new Dialog(BaseActivity.this, R.style.NoBackGroundDialog);
                    View v = LayoutInflater.from(BaseActivity.this).inflate(R.layout.dialog_nb, null);
                    TextView tvNumber = (TextView) v.findViewById(R.id.dialog_tv_nb_number);
                    TextView tvInfo = (TextView) v.findViewById(R.id.dialog_tv_nb_info);
                    TextView tvFinish = (TextView) v.findViewById(R.id.dialog_tv_nb_finish);
                    tvNumber.setText(MessageFormat.format("农币+{0}", pointVOList.get(i).getPointValue()));
                    tvInfo.setText(pointVOList.get(i).getRemark());
                    tvFinish.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    dialog.setCancelable(false);
                    dialog.setContentView(v);
                    dialog.show();
                }

            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (getIntent().hasExtra("pointVOList")) {
            List<PointVO> pointVOList = (List<PointVO>) getIntent().getSerializableExtra("pointVOList");
            if (pointVOList != null && pointVOList.size() > 0) {
                for (int i = 0; i < pointVOList.size(); i++) {
                    final Dialog dialog = new Dialog(BaseActivity.this, R.style.NoBackGroundDialog);
                    View v = LayoutInflater.from(BaseActivity.this).inflate(R.layout.dialog_nb, null);
                    TextView tvNumber = (TextView) v.findViewById(R.id.dialog_tv_nb_number);
                    TextView tvInfo = (TextView) v.findViewById(R.id.dialog_tv_nb_info);
                    TextView tvFinish = (TextView) v.findViewById(R.id.dialog_tv_nb_finish);
                    tvNumber.setText(MessageFormat.format("农币+{0}", pointVOList.get(i).getPointValue()));
                    tvInfo.setText(pointVOList.get(i).getRemark());
                    tvFinish.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    dialog.setCancelable(false);
                    dialog.setContentView(v);
                    dialog.show();
                }

            }
            getIntent().removeExtra("pointVOList");
        }

        // 百度统计
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 百度统计
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 根据Tag取消Post请求
        OkHttpUtils.getInstance().cancelTag(this);
        // 把当前activity溢除栈
        ActivityTaskManager.getInstance().removeActivity(this);
        // 解绑View
        ButterKnife.unbind(this);
    }

    /**
     * 设置标题
     *
     * @param title
     */
    protected void setTitle(String title) {

        if (null != mTextViewTitle)
            mTextViewTitle.setText(title);

    }

    protected void setNoTitle() {
    }

    /**
     * 设置右上角按钮文本
     *
     * @param title
     */
    protected void setRightText(String title) {

        if (null != mTvRight) {
            mTvRight.setText(title);
            mTvRight.setVisibility(View.VISIBLE);
        }

    }


    /**
     * 设置右上角图标按钮
     *
     * @param resId
     */
    protected void setRightImage(int resId) {

        if (null != mIvRight) {
            mIvRight.setImageResource(resId);
            mIvRight.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置右上角图标按钮
     *
     * @param resId
     */
    protected void setRightImage2(int resId) {

        if (null != mIvRight2) {
            mIvRight2.setImageResource(resId);
            mIvRight2.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏ActionBar
     */
    protected void hideActionBar() {

        mViewGroupActionBar.setVisibility(View.GONE);

    }

    /**
     * 展示ctionBar
     */
    protected void showActionBar() {

        mViewGroupActionBar.setVisibility(View.VISIBLE);

    }

    /**
     * 无参跳转
     *
     * @param activity
     */
    protected void go(Class activity) {
        GotoUtil.gotoActivity(this, activity);
    }

    /**
     * 有参跳转
     *
     * @param activity
     */
    protected void go(Class activity, String key, Object pmExtra) {
        GotoUtil.gotoActivity(this, activity, key, pmExtra);
    }

    /**
     * 隐藏左上角返回按钮
     */
    protected void hideBackBtn() {
        mIvBack.setVisibility(View.GONE);
    }


    public void hideKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(mViewGroupContent.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 判断登录，状态未登录跳转至登录页面
     */
    public boolean noLoginToSkip() {
        boolean isLogin = false;
        if ("1".equals(UserXML.getLoginStatus(this))) {
            isLogin = true;
        } else {
            GotoUtil.gotoActivity(this, LoginActivity.class);
        }
        return isLogin;
    }
}
